package com.atom.app.mvi.net

import android.util.Log
import com.atom.app.mvi.net.interceptor.LoggingInterceptor
import com.atom.app.mvi.net.interceptor.SessionInterceptor
import com.atom.app.mvi.utils.JacksonUtils
import com.moczul.ok2curl.CurlInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.jackson.JacksonConverterFactory

typealias CurlLogger = com.moczul.ok2curl.logger.Logger

object RetrofitFactory {

    fun createClient(listener: (OkHttpClient.Builder) -> Unit = {}): OkHttpClient {
        val client = OkHttpClient.Builder()
        listener.invoke(client)
        client.addInterceptor(CurlInterceptor(object : CurlLogger {
            override fun log(message: String) {
                Log.i("LoggingI", message)
            }
        }))
        client.addInterceptor(SessionInterceptor())
        client.addNetworkInterceptor(
            LoggingInterceptor.Builder()
            .addHeader("Content-Type", "application/json")
            .addHeader("v", "200")
            .build())
        return client.build()
    }

    fun createRetrofit(
        url: String,
        client: OkHttpClient,
        block: (Retrofit.Builder) -> Unit = {}
    ): Retrofit {
        val retrofitBuilder: Retrofit.Builder = Retrofit.Builder()
            .baseUrl(url)
            .client(client)
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .addConverterFactory(JacksonConverterFactory.create(JacksonUtils.objectMapper))
        block.invoke(retrofitBuilder)
        return retrofitBuilder.build()
    }

}
